﻿using System;
using System.Web;
using System.Globalization;
using Fuse8.DomainFramework.Common;
using Fuse8.DomainFramework.Domain;

namespace Fuse8.DomainFramework.DataAccess
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class HttpContextUnitOfWorkFactory<T> : IUnitOfWorkFactory<T>
        where T : class, IEntityObject, new()
    {
        private static readonly string _typeParameter = new T().TypeParameter;

        private HttpContextBase _currentContext;

        /// <summary>
        /// 
        /// </summary>
        public HttpContextBase CurrentHttpContext
        {
            get
            {
                return _currentContext != null ?
                    _currentContext :
                    HttpContext.Current != null ?
                        new HttpContextWrapper(HttpContext.Current) as HttpContextBase :
                        DummyHttpContext.GetInstance();
            }
            set
            {
                _currentContext = value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        protected virtual string FactoryKeyFormat
        {
            get
            {
                return "HttpCurrentUnitOfWork_{0}";
            }
        }

        #region IUnitOfWorkFactory Members

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public abstract IUnitOfWork<T> Create(bool withTransaction);

        /// <summary>
        /// 
        /// </summary>
        public abstract void CommitTransaction();

        /// <summary>
        /// 
        /// </summary>
        public abstract void RollbackTransaction();

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TMain"></typeparam>
        /// <param name="unitOfWork"></param>
        /// <returns></returns>
        public abstract IUnitOfWork<T> CreateFrom<TMain>(IUnitOfWork<TMain> unitOfWork) where TMain : class, IEntityObject;

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public virtual IUnitOfWork<T> Get(bool withTransaction)
        {
            return InnerGet(withTransaction, true);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TMain"></typeparam>
        /// <param name="unitOfWork"></param>
        public virtual void UseFrom<TMain>(IUnitOfWork<TMain> unitOfWork) where TMain : class, IEntityObject
        {
            CurrentHttpContext.Items[GenerateFactoryKeyForTransaction()] = CreateFrom(unitOfWork);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public virtual string GenerateFactoryKey()
        {
            return string.Format(CultureInfo.InvariantCulture, FactoryKeyFormat, _typeParameter);
        }

        /// <summary>
        /// 
        /// </summary>        
        public virtual void Close()
        {
            var transactionalUnitOfWork = InnerGet(true, false);
            if (transactionalUnitOfWork != null)
            {
                transactionalUnitOfWork.Dispose();

                CurrentHttpContext.Items.Remove(GenerateFactoryKeyForTransaction());
            }

            var unitOfWork = InnerGet(false, false);
            if (unitOfWork != null)
            {
                unitOfWork.Dispose();

                CurrentHttpContext.Items.Remove(GenerateFactoryKey());
            }
        }

        public virtual object GetSimple(bool withTransaction)
        {
            return InnerGet(withTransaction, true);
        }

        #endregion

        #region Private methods

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected virtual string GenerateFactoryKeyForTransaction()
        {
            return string.Format("{0}_in_transaction", GenerateFactoryKey());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="withTransaction"></param>
        /// <param name="needCreateIfNotFound"></param>
        /// <returns></returns>
        protected virtual IUnitOfWork<T> InnerGet(bool withTransaction, bool needCreateIfNotFound)
        {
            string factoryKey = GenerateFactoryKeyForTransaction();

            var result = CurrentHttpContext.Items[factoryKey] as IUnitOfWork<T>;

            if ((result == null) && !withTransaction)
            {
                factoryKey = GenerateFactoryKey();
                result = CurrentHttpContext.Items[factoryKey] as IUnitOfWork<T>;
            }

            if ((result == null) && needCreateIfNotFound)
            {
                result = Create(withTransaction);

                CurrentHttpContext.Items[factoryKey] = result;
            }

            return result;
        }

        #endregion
    }
}
